package com.pan.test.controller;

import com.pan.test.annotation.GlobalInterceptor;
import com.pan.test.annotation.VerifyParam;
import com.pan.test.component.RedisComponent;
import com.pan.test.entity.constants.Constants;
import com.pan.test.entity.dto.SysSettingsDto;
import com.pan.test.entity.po.FileInfo;
import com.pan.test.entity.po.OrderInfo;
import com.pan.test.entity.po.UserInfo;
import com.pan.test.entity.query.FileInfoQuery;
import com.pan.test.entity.query.UserInfoQuery;
import com.pan.test.entity.vo.PaginationResultVO;
import com.pan.test.entity.vo.ResponseVO;
import com.pan.test.entity.vo.UserInfoVO;
import com.pan.test.exception.BusinessException;
import com.pan.test.mappers.OrderMapper;
import com.pan.test.service.FileInfoService;
import com.pan.test.service.UserInfoService;
import com.pan.test.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController("adminController")
@RequestMapping("/admin")
public class AdminController extends CommonFileController {

    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    // 注入RedisComponent
    @Resource
    private RedisComponent redisComponent;

    // 注入UserInfoService
    @Resource
    private UserInfoService userInfoService;

    // 注入FileInfoService
    @Resource
    private FileInfoService fileInfoService;

    @Resource
    private OrderMapper orderMapper;

    // 获取系统设置
    @RequestMapping("/getSysSettings")
    // 全局拦截器，检查参数和是否为管理员
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO getSysSettings() {
        // 调用RedisComponent的getSysSettingsDto方法获取系统设置
        return getSuccessResponseVO(redisComponent.getSysSettingsDto());
    }

    // 保存系统设置
    @RequestMapping("/saveSysSettings")
    // 全局拦截器，检查参数和是否为管理员
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO saveSysSettings(
                // 验证参数，必填
                @VerifyParam(required = true) String registerEmailTitle,
                // 验证参数，必填
                @VerifyParam(required = true) String registerEmailContent,
                // 验证参数，必填
                @VerifyParam(required = true) Integer userInitUseSpace) {
        // 创建SysSettingsDto对象
        SysSettingsDto sysSettingsDto = new SysSettingsDto();
        // 设置注册邮件标题
        sysSettingsDto.setRegisterEmailTitle(registerEmailTitle);
        // 设置注册邮件内容
        sysSettingsDto.setRegisterEmailContent(registerEmailContent);
        // 设置用户初始使用空间
        sysSettingsDto.setUserInitUseSpace(userInitUseSpace);
        // 调用RedisComponent的saveSysSettingsDto方法保存系统设置
        redisComponent.saveSysSettingsDto(sysSettingsDto);
        // 返回成功响应
        return getSuccessResponseVO(null);
    }

    // 加载用户列表
    @RequestMapping("/loadUserList")
    // 全局拦截器，检查参数和是否为管理员
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO loadUser(UserInfoQuery userInfoQuery) {
        userInfoQuery.setOrderBy("join_time desc");
        PaginationResultVO<UserInfo> resultVO = userInfoService.findListByPage(userInfoQuery);
        return getSuccessResponseVO(convert2PaginationVO(resultVO, UserInfoVO.class));
    }

    @RequestMapping("/updateUserStatus")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO updateUserStatus(@VerifyParam(required = true) String userId, @VerifyParam(required = true) Integer status) {
        userInfoService.updateUserStatus(userId, status);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/updateUserSpace")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO updateUserSpace(@VerifyParam(required = true) String userId, @VerifyParam(required = true) Integer changeSpace) {
        userInfoService.changeUserSpace(userId, changeSpace);
        return getSuccessResponseVO(null);
    }

    /**
     * 查询所有文件
     *
     * @param query
     * @return
     */
    @RequestMapping("/loadFileList")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO loadDataList(FileInfoQuery query) {
        query.setOrderBy("last_update_time desc");
        query.setQueryNickName(true);
        query.setDelFlag(2);  // 添加删除标记条件
        PaginationResultVO resultVO = fileInfoService.findListByPage(query);
        return getSuccessResponseVO(resultVO);
    }

    @RequestMapping("/getFolderInfo")
    @GlobalInterceptor(checkLogin = false,checkAdmin = true, checkParams = true)
    public ResponseVO getFolderInfo(@VerifyParam(required = true) String path) {
        return super.getFolderInfo(path, null);
    }

    @RequestMapping("/getFile/{userId}/{fileId}")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public void getFile(HttpServletResponse response,
                        @PathVariable("userId") @VerifyParam(required = true) String userId,
                        @PathVariable("fileId") @VerifyParam(required = true) String fileId) {
        super.getFile(response, fileId, userId);
    }

    @RequestMapping("/ts/getVideoInfo/{userId}/{fileId}")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public void getVideoInfo(HttpServletResponse response,
                             @PathVariable("userId") @VerifyParam(required = true) String userId,
                             @PathVariable("fileId") @VerifyParam(required = true) String fileId) {
        super.getFile(response, fileId, userId);
    }

    @RequestMapping("/createDownloadUrl/{userId}/{fileId}")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO createDownloadUrl(@PathVariable("userId") @VerifyParam(required = true) String userId,
                                        @PathVariable("fileId") @VerifyParam(required = true) String fileId) {
        return super.createDownloadUrl(fileId, userId);
    }

    /**
     * 下载
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/download/{code}")
    // 不检查登录，检查参数
    @GlobalInterceptor(checkLogin = false, checkParams = true)
    public void download(HttpServletRequest request, HttpServletResponse response,
                         // 路径变量，必填
                         @PathVariable("code") @VerifyParam(required = true) String code) throws Exception {
        // 调用父类的download方法
        super.download(request, response, code);
    }

    @RequestMapping("/delFile")
    // 全局拦截器，检查参数和是否为管理员
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO delFile(@VerifyParam(required = true) String fileIdAndUserIds) {
        // 将传入的字符串按照逗号分隔，得到一个数组
        String[] fileIdAndUserIdArray = fileIdAndUserIds.split(",");
        // 遍历数组
        for (String fileIdAndUserId : fileIdAndUserIdArray) {
            // 将每个元素按照下划线分隔，得到一个数组
            String[] itemArray = fileIdAndUserId.split("_");
            // 调用文件信息服务，删除文件
            fileInfoService.delFileBatch(itemArray[0], itemArray[1], true);
        }
        // 返回成功响应
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/dashboard/stats")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO getDashboardStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取总用户数
        UserInfoQuery userQuery = new UserInfoQuery();
        stats.put("totalUsers", userInfoService.findCount(userQuery));
        
        // 获取今日新增用户数
        userQuery = new UserInfoQuery();
        userQuery.setJoinTimeStart(DateUtil.getToday());
        userQuery.setJoinTimeEnd(DateUtil.getTomorrow());
        stats.put("newUsersToday", userInfoService.findCount(userQuery));
        
        // 获取文件统计
        FileInfoQuery fileQuery = new FileInfoQuery();
        fileQuery.setDelFlag(2);  // 添加删除标记条件
        stats.put("totalFiles", fileInfoService.findCount(fileQuery));
        
        // 获取总存储空间使用量
        stats.put("totalStorage", fileInfoService.getTotalFileSize());
        
        return getSuccessResponseVO(stats);
    }

    @RequestMapping("/dashboard/storage/trend")
    @GlobalInterceptor(checkParams = false, checkAdmin = true)
    public ResponseVO getStorageTrend(@RequestParam(defaultValue = "7") Integer days) {
        try {
            String startDate = DateUtil.getBeforeDaysDate(days);
            String endDate = DateUtil.getToday();
            logger.info("查询存储趋势，开始日期：{}，结束日期：{}", startDate, endDate);
            
            List<Map<String, Object>> trend = fileInfoService.getStorageTrend(days);
            
            // 添加调试日志
            if (trend != null) {
                logger.info("成功获取存储趋势数据，数据条数：{}", trend.size());
                for (Map<String, Object> data : trend) {
                    logger.info("日期：{}，存储空间：{}，文件数：{}，文件类型：{}", 
                        data.get("date"), 
                        data.get("storage"), 
                        data.get("file_count"),
                        data.get("debug_folder_types"));
                }
            } else {
                logger.warn("获取存储趋势数据为空");
            }
            
            // 移除调试信息后再返回给前端
            if (trend != null) {
                for (Map<String, Object> data : trend) {
                    data.remove("debug_folder_types");
                }
            }
            
            return getSuccessResponseVO(trend);
        } catch (Exception e) {
            logger.error("获取存储趋势数据失败", e);
            return getSuccessResponseVO(new ArrayList<>());
        }
    }

    @RequestMapping("/dashboard/userTrend")
    @GlobalInterceptor(checkParams = false, checkAdmin = true)
    public ResponseVO getUserTrend(@RequestParam(defaultValue = "7") Integer days) {
        try {
            List<Map<String, Object>> trend = userInfoService.getUserTrend(days);
            return getSuccessResponseVO(trend);
        } catch (Exception e) {
            logger.error("获取用户趋势数据失败", e);
            return getSuccessResponseVO(new ArrayList<>());
        }
    }

    @RequestMapping("/dashboard/fileTypeDist")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO getFileTypeDistribution() {
        List<Map<String, Object>> distribution = fileInfoService.getFileTypeDistribution();
        return getSuccessResponseVO(distribution);
    }

    @RequestMapping("/user/create")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO createUser(@VerifyParam(required = true) String email,
                               @VerifyParam(required = true) String nickName,
                               @VerifyParam(required = true) String password,
                               @VerifyParam(required = true) Integer useSpace) {
        userInfoService.createUser(email, nickName, password, useSpace);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/user/delete")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO deleteUser(@VerifyParam(required = true) String userId) {
        userInfoService.deleteUser(userId);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/user/update")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO updateUser(@VerifyParam(required = true) String userId,
                               String nickName,
                               String password,
                               Integer status,
                               Integer useSpace) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setNickName(nickName);
        userInfo.setPassword(password);
        userInfo.setStatus(status);
        if (useSpace != null) {
            userInfo.setTotalSpace(useSpace * Constants.MB);
        }
        userInfoService.updateUserInfo(userInfo);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/user/info")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO getUserInfo(@VerifyParam(required = true) String userId) {
        return getSuccessResponseVO(userInfoService.getUserInfo(userId));
    }

    @RequestMapping("/user/search")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO searchUsers(UserInfoQuery userInfoQuery) {
        userInfoQuery.setOrderBy("join_time desc");
        return getSuccessResponseVO(userInfoService.findListByPage(userInfoQuery));
    }

    @RequestMapping("/settings/email")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO updateEmailSettings(
            @VerifyParam(required = true) String smtpServer,
            @VerifyParam(required = true) String smtpPort,
            @VerifyParam(required = true) String smtpUsername,
            @VerifyParam(required = true) String smtpPassword) {
        SysSettingsDto sysSettingsDto = redisComponent.getSysSettingsDto();
        sysSettingsDto.setSmtpServer(smtpServer);
        sysSettingsDto.setSmtpPort(smtpPort);
        sysSettingsDto.setSmtpUsername(smtpUsername);
        sysSettingsDto.setSmtpPassword(smtpPassword);
        redisComponent.saveSysSettingsDto(sysSettingsDto);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/settings/storage")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO updateStorageSettings(
            @VerifyParam(required = true) Integer defaultUserSpace,
            @VerifyParam(required = true) Integer maxFileSize,
            @VerifyParam(required = true) String allowedFileTypes) {
        SysSettingsDto sysSettingsDto = redisComponent.getSysSettingsDto();
        sysSettingsDto.setUserInitUseSpace(defaultUserSpace);
        sysSettingsDto.setMaxFileSize(maxFileSize);
        sysSettingsDto.setAllowedFileTypes(allowedFileTypes);
        redisComponent.saveSysSettingsDto(sysSettingsDto);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/dashboard/overview")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO getDashboardOverview() {
        Map<String, Object> overview = new HashMap<>();
        
        try {
            // 用户统计
            UserInfoQuery userQuery = new UserInfoQuery();
            overview.put("totalUsers", userInfoService.findCount(userQuery));
            
            // 今日新增用户
            userQuery = new UserInfoQuery();
            userQuery.setJoinTimeStart(DateUtil.getToday());
            userQuery.setJoinTimeEnd(DateUtil.getTomorrow());
            overview.put("newUsersToday", userInfoService.findCount(userQuery));
            
            // 文件统计
            FileInfoQuery fileQuery = new FileInfoQuery();
            overview.put("totalFiles", fileInfoService.findCount(fileQuery));
            
            // 总存储空间使用量（转换为MB）
            Long totalStorage = fileInfoService.getTotalFileSize();
            overview.put("totalStorage", totalStorage);
            
            return getSuccessResponseVO(overview);
        } catch (Exception e) {
            logger.error("获取仪表盘概览数据失败", e);
            return getSuccessResponseVO(overview);
        }
    }

    @RequestMapping("/dashboard/activity")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO getRecentActivity() {
        try {
            FileInfoQuery query = new FileInfoQuery();
            query.setPageSize(10);
            query.setPageNo(1);
            query.setOrderBy("last_update_time desc");
            query.setQueryNickName(true);
            query.setDelFlag(2);  // 添加删除标记条件
            PaginationResultVO<FileInfo> result = fileInfoService.findListByPage(query);
            return getSuccessResponseVO(result.getList());
        } catch (Exception e) {
            logger.error("获取最近活动数据失败", e);
            return getSuccessResponseVO(new ArrayList<>());
        }
    }

    /**
     * 搜索文件
     */
    @RequestMapping("/files/search")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO searchFiles(@VerifyParam(required = true) String keyword) {
        try {
            List<Map<String, Object>> files = fileInfoService.searchFiles(keyword);
            return getSuccessResponseVO(files);
        } catch (Exception e) {
            logger.error("搜索文件失败", e);
            return new ResponseVO<List<Map<String, Object>>>(0, e.getMessage(), null);
        }
    }

    /**
     * 批量删除文件
     */
    @RequestMapping("/files/batchDelete")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO batchDeleteFiles(@VerifyParam(required = true) String fileIds) {
        try {
            List<String> fileIdList = Arrays.asList(fileIds.split(","));
            fileInfoService.batchDeleteFiles(fileIdList);
            return getSuccessResponseVO(null);
        } catch (Exception e) {
            logger.error("批量删除文件失败", e);
            return new ResponseVO<Void>(0, e.getMessage(), null);
        }
    }

    /**
     * 下载文件
     */
    @RequestMapping("/files/download/{fileId}")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public void downloadFile(HttpServletResponse response, 
                           @PathVariable("fileId") @VerifyParam(required = true) String fileId) {
        try {
            Map<String, Object> fileInfo = fileInfoService.getFileDownloadInfo(fileId);
            if (fileInfo == null) {
                throw new BusinessException("文件不存在或已被删除");
            }

            String filePath = (String) fileInfo.get("file_path");
            String fileName = (String) fileInfo.get("file_name");
            Long fileSize = ((Number) fileInfo.get("file_size")).longValue();

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + 
                             URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Content-Length", String.valueOf(fileSize));

            try (FileInputStream fis = new FileInputStream(filePath);
                 BufferedInputStream bis = new BufferedInputStream(fis);
                 OutputStream os = response.getOutputStream()) {
                
                byte[] buffer = new byte[1024];
                int i;
                while ((i = bis.read(buffer)) != -1) {
                    os.write(buffer, 0, i);
                }
                os.flush();
            }
        } catch (Exception e) {
            logger.error("下载文件失败", e);
            throw new BusinessException("下载文件失败");
        }
    }

    /**
     * 获取支付统计数据
     */
    @RequestMapping("/payment/stats")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO<Map<String, Object>> getPaymentStats() {
        try {
            logger.info("==================== 开始获取支付统计数据 ====================");
            
            Map<String, Object> result = new HashMap<>();
            
            // 获取总交易金额
            BigDecimal totalAmount = orderMapper.getTotalAmount();
            result.put("totalAmount", totalAmount);
            logger.info("总交易金额：￥{}", totalAmount);
            
            // 获取总订单数
            Integer totalOrders = orderMapper.getTotalOrders();
            result.put("totalOrders", totalOrders);
            logger.info("总订单数：{} 笔", totalOrders);
            
            // 获取今日订单数
            Integer todayOrders = orderMapper.getTodayOrders();
            result.put("todayOrders", todayOrders);
            logger.info("今日订单数：{} 笔", todayOrders);
            
            // 获取支付成功率
            BigDecimal successRate = orderMapper.getSuccessRate();
            result.put("successRate", successRate);
            logger.info("支付成功率：{}%", successRate);
            
            // 获取最近交易记录
            List<Map<String, Object>> recentOrders = orderMapper.getRecentOrders();
            result.put("recentOrders", recentOrders);
            logger.info("最近交易记录数：{}", recentOrders.size());
            
            // 打印每条最近交易记录的详细信息
            if (recentOrders != null && !recentOrders.isEmpty()) {
                logger.info("最近交易记录详情：");
                logger.info("--------------------------------------------");
                for (Map<String, Object> order : recentOrders) {
                    logger.info("订单号：{}", order.get("orderId"));
                    logger.info("套餐名称：{}", order.get("packageName"));
                    logger.info("支付金额：￥{}", order.get("amount"));
                    logger.info("支付方式：{}", "alipay".equals(order.get("paymentMethod")) ? "支付宝" : "微信支付");
                    logger.info("支付状态：{}", getStatusText((Integer)order.get("status")));
                    logger.info("创建时间：{}", order.get("createTime"));
                    logger.info("支付时间：{}", order.get("payTime"));
                    logger.info("--------------------------------------------");
                }
            }
            
            logger.info("==================== 获取支付统计数据结束 ====================");
            return ResponseVO.success(result);
        } catch (Exception e) {
            logger.error("获取支付统计数据失败", e);
            return ResponseVO.error("获取支付统计数据失败：" + e.getMessage());
        }
    }

    // 获取状态文本
    private String getStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0: return "待支付";
            case 1: return "已支付";
            case 2: return "已取消";
            case 3: return "支付失败";
            default: return "未知";
        }
    }

    /**
     * 获取支付趋势数据
     */
    @RequestMapping("/payment/trend")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO<Map<String, Object>> getPaymentTrend(@RequestParam String timeRange) {
        try {
            logger.info("==================== 开始获取支付趋势数据 ====================");
            logger.info("时间范围：{}", timeRange);
            
            Date endDate = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endDate);
            
            // 根据时间范围设置开始日期
            int days = "week".equals(timeRange) ? 7 : ("month".equals(timeRange) ? 30 : 365);
            calendar.add(Calendar.DAY_OF_YEAR, -days);
            Date startDate = calendar.getTime();
            
            // 获取趋势数据
            List<Map<String, Object>> trendData = orderMapper.getPaymentTrendData(startDate, endDate);
            logger.info("查询到{}条趋势数据", trendData.size());
            
            Map<String, Object> result = new HashMap<>();
            result.put("data", trendData);
            
            logger.info("==================== 获取支付趋势数据结束 ====================");
            return ResponseVO.success(result);
        } catch (Exception e) {
            logger.error("获取支付趋势数据失败", e);
            return ResponseVO.error("获取支付趋势数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取支付方式统计
     */
    @RequestMapping("/payment/typeStats")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO<Map<String, Object>> getPaymentTypeStats() {
        try {
            logger.info("==================== 开始获取支付方式统计 ====================");
            
            List<Map<String, Object>> stats = orderMapper.getPaymentMethodStats();
            logger.info("查询到{}种支付方式的统计数据", stats.size());
            
            Map<String, Object> result = new HashMap<>();
            result.put("data", stats);
            
            logger.info("==================== 获取支付方式统计结束 ====================");
            return ResponseVO.success(result);
        } catch (Exception e) {
            logger.error("获取支付方式统计失败", e);
            return ResponseVO.error("获取支付方式统计失败：" + e.getMessage());
        }
    }

    /**
     * 获取支付订单列表
     */
    @RequestMapping("/payment/list")
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    public ResponseVO getPaymentList(@RequestParam(required = false) String orderNo,
                                   @RequestParam(required = false) String payType,
                                   @RequestParam(required = false) String status,
                                   @RequestParam(required = false) String startTime,
                                   @RequestParam(required = false) String endTime,
                                   @RequestParam(defaultValue = "1") Integer pageNo,
                                   @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            logger.info("==================== 开始查询支付列表 ====================");
            logger.info("查询参数：orderNo={}, payType={}, status={}, startTime={}, endTime={}, pageNo={}, pageSize={}", 
                orderNo, payType, status, startTime, endTime, pageNo, pageSize);
                
            // 获取订单总数
            Integer total = orderMapper.getOrderCount(orderNo, payType, status, startTime, endTime);
            logger.info("查询到的订单总数：{}", total);
            
            // 计算偏移量
            int offset = (pageNo - 1) * pageSize;
            logger.info("分页参数：offset={}, pageSize={}", offset, pageSize);
            
            // 获取订单列表
            List<Map<String, Object>> list = orderMapper.getOrderList(orderNo, payType, status, startTime, endTime, 
                offset, pageSize);
            
            logger.info("查询结果：total={}, listSize={}", total, list != null ? list.size() : 0);
            
            // 打印每条记录的详细信息
            if (list != null && !list.isEmpty()) {
                logger.info("订单详细信息：");
                for (Map<String, Object> order : list) {
                    logger.info("--------------------------------------------------");
                    logger.info("订单号：{}", order.get("orderId"));
                    logger.info("套餐ID：{}", order.get("packageId"));
                    logger.info("套餐名称：{}", order.get("packageName"));
                    logger.info("支付金额：{}", order.get("amount"));
                    logger.info("支付方式：{}", order.get("paymentMethod"));
                    logger.info("支付状态：{}", order.get("status"));
                    logger.info("创建时间：{}", order.get("createTime"));
                    logger.info("支付时间：{}", order.get("payTime"));
                }
                logger.info("--------------------------------------------------");
            } else {
                logger.info("没有查询到订单数据");
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", list != null ? list : new ArrayList<>());
            result.put("total", total != null ? total : 0);
            
            logger.info("==================== 查询支付列表结束 ====================");
            return ResponseVO.success(result);
        } catch (Exception e) {
            logger.error("获取支付列表失败", e);
            return ResponseVO.error("获取支付列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取支付订单详情
     */
    @RequestMapping("/payment/detail")
    public ResponseVO<Map<String, Object>> getPaymentDetail(@RequestParam String orderNo) {
        // TODO: 从数据库获取实际数据
        Map<String, Object> detail = new HashMap<>();
        detail.put("orderNo", orderNo);
        detail.put("userName", "测试用户");
        detail.put("productName", "高级会员套餐");
        detail.put("amount", 9900);
        detail.put("payType", "alipay");
        detail.put("status", 1);
        detail.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        detail.put("payTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        detail.put("tradeNo", "T" + System.currentTimeMillis());
        
        return ResponseVO.success(detail);
    }

    /**
     * 导出支付订单数据
     */
    @RequestMapping("/payment/export")
    public void exportPayments(HttpServletResponse response,
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) String payType,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) throws Exception {
        
        // TODO: 从数据库获取实际数据并生成Excel
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=payment_orders.xlsx");
        
        // 这里只是一个示例，实际应该使用POI等库生成Excel
        String content = "订单号,用户,金额,支付方式,状态,创建时间,支付时间\n";
        content += "ORD123,用户A,99.00,支付宝,已支付,2024-03-20 10:00:00,2024-03-20 10:01:00\n";
        
        response.getOutputStream().write(content.getBytes());
    }
}
